import React, { Component } from 'react'
import { StyleSheet, SafeAreaView } from 'react-native'
import md5 from 'js-md5'
import { px2dp, isAndroid, showToast } from 'rn-xiaobu-utils'
import ajaxAsync from '../../../src/utils/ajaxAsync'
import { getTitleBarOptions } from '../../../src/utils/DefaultTitleOption'

import PhoneInput from '../../components/login/logininput/PhoneInput'
import PasswordInput from '../../components/login/logininput/PasswordInput'
import CodeInput from '../../components/login/logininput/CodeInput'
import LoginBtn from '../../components/login/loginbtn/LoginBtn'
import { setUserInfo } from '../../../src/utils/UserBean'
import { cityappname } from '../../../src/configs/api'

export default class RegistryPage extends Component {
  static navigationOptions = ({ navigation }) => {
    let pageTitle = navigation.getParam('isForget', false)
      ? '忘记密码'
      : '注册账号'
    return getTitleBarOptions({ navigation }, { headerTitle: pageTitle })
  }

  constructor (props) {
    super(props)

    this.isForget = this.props.navigation.getParam('isForget', false)
    this.smsPostUrl = this.isForget ? '/user/smscode/forget' : '/user/smscode/register'
  }

  // 自定义的函数都使用定义属性的写法，否则会取不到this
  _onLoginButton = () => {
    Promise.all([
      this.refs.phoneInput._validText(),
      this.refs.codeInput._validText(),
      this.refs.passwordInput._validText()
    ]).then(result => {
      if (this.isForget) {
        this._forgetPwd(...result)
      } else {
        this._appRegister(...result)
      }
    }).catch(err => {
      showToast(err.message)
    })
  }

  _appRegister = (phone, code, password) => {
    let sendObj = {
      PHONE: phone,
      SMS_CODE: code,
      PASSWORD_MD5: md5(password)
    }
    ajaxAsync('/user/city/register', sendObj).then(body => {
      // TODO: 注册成功
      body.IS_LOGIN = 1
      body.PHONE = phone
      setUserInfo(body).then(() => {
        showToast('欢迎来到' + cityappname)
        this.props.navigation.dismiss()
      })
    })
  }

  _forgetPwd = (phone, code, password) => {
    let sendObj = {
      PHONE: phone,
      SMS_CODE: code,
      PASSWORD_MD5: md5(password),
      MOBILE_MODEL: isAndroid() ? 1 : 0
    }
    ajaxAsync('/user/city/change', sendObj).then(() => {
      // TODO: 忘记密码
      setUserInfo().then(() => {
        showToast('密码设置成功,请重新登陆')
        this.props.navigation.goBack()
      })
    })
  }

  _getCode = () => {
    this.refs.phoneInput._validText().then(phone => {
      let sendObj = {
        PHONE: phone
      }
      ajaxAsync(this.smsPostUrl, sendObj).then(() => {
        showToast('验证码发送成功')
        this.refs.codeInput._countDown()
      })
    }).catch(err => {
      showToast(err.message)
    })
  }

  render () {
    return (
      <SafeAreaView style={styles.container}>
        <PhoneInput ref="phoneInput"/>
        <CodeInput ref="codeInput" getCode={this._getCode}/>
        <PasswordInput ref="passwordInput"/>
        <LoginBtn text="确定" onPress={this._onLoginButton}/>
      </SafeAreaView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    alignItems: 'center',
    backgroundColor: '#ffffff',
    // backgroundColor: '#aff',
    paddingLeft: px2dp(30),
    paddingRight: px2dp(30),
    position: 'relative'
  }
})
